﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Arch.Intercep;

namespace Arch.Aspects
{
    [AttributeUsage(AttributeTargets.Property)]
    public class Increment : Attribute, IMemberAspectInterceptor
    {
        public int IncrementValue { get; set; }

        public Increment() : this(1) { }

        public Increment(int incrementValue)
        {
            IncrementValue = incrementValue;
            Targets = ActionTarget.Creating | ActionTarget.Updating | ActionTarget.Deleting;
        }

        public Increment(ActionTarget targets)
        {
            IncrementValue = 1;
            Targets = targets;
        }

        public Increment(int incrementValue, ActionTarget targets)
        {
            IncrementValue = incrementValue;
            Targets = targets;
        }

        public void Intercept(object entity, MemberInfo member)
        {
            var propertyInfo = member as PropertyInfo;
            if (propertyInfo == null) return;

            object oldValue = propertyInfo.GetGetMethod().Invoke(entity, new object[0]);
            object newValue = null;
            if (propertyInfo.PropertyType.Equals(typeof(int)))
                newValue = (int)oldValue + IncrementValue;
            else if (propertyInfo.PropertyType.Equals(typeof(long)))
                newValue = (long)oldValue + IncrementValue;
            else if (propertyInfo.PropertyType.Equals(typeof(uint)))
                newValue = (uint)oldValue + IncrementValue;
            else if (propertyInfo.PropertyType.Equals(typeof(byte)))
                newValue = (byte)oldValue + IncrementValue;

            propertyInfo.GetSetMethod().Invoke(entity, new object[] { newValue });
        }

        public ActionTarget Targets { get; protected set; }
    }
}